package com.atguigu.yygh.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.orders.service.OrderInfoService;
import com.atguigu.yygh.orders.service.PaymentInfoService;
import com.atguigu.yygh.orders.service.RefundInfoService;
import com.atguigu.yygh.orders.service.WeixinService;
import com.atguigu.yygh.orders.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.orders.utils.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RefundInfoService refundInfoService;


    //微信退款
    @Override
    public Boolean refund(Long orderId) {
        //根据订单号查询支付记录 （使用到交易号）
        PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(orderId);
        if (paymentInfo == null) {
            return false;
        }
        //添加退款记录到退款记录表
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        //封装微信退款接口需要的参数
        Map<String, String> paramMap = new HashMap<>(8);
        paramMap.put("appid", ConstantPropertiesUtils.APPID);       //公众账号ID
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);   //商户编号
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        paramMap.put("transaction_id", paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("out_trade_no", paymentInfo.getOutTradeNo()); //商户订单流水编号
        paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo()); //商户退款单号
        //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee", "1");
        paramMap.put("refund_fee", "1");


        try {
            //使用httpclient请求微信退款接口完成退款
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            //是否使用证书
            client.setCert(true);
            //设置证书密码：商户号
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();

            //返回结果
            String xml = client.getContent();
            System.out.println("xml = " + xml);//退款后返回的数据
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //根据订单号查询支付状态
    @Override
    public Map queryPayStatus(Long orderId, String paymentType) {
        //根据订单号查询订单数据
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
        //封装微信参数
        Map paramMap = new HashMap<>();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);//公众号id
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());//交易号 流水号
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());


        try {
            //调用httpclient
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //得到微信支付状态查询接口返回的数据
            String xml = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            System.out.println("xml = " + xml);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据订单号生成微信付款二维码
    @Override
    public Map<String, Object> createNativeWx(Long orderId) {
        //根据id查询订单信息
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);


        //订单信息添加支付记录表 1 zfb 2vx
        paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());


        try {
            //封装微信二维码接口需要数据
            Map paramMap = new HashMap();
            //公众号id
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            //商户号
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            //传递随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            Date reserveDate = orderInfo.getReserveDate();
            String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊" + orderInfo.getHosname() + "--" + orderInfo.getDepname();
            paramMap.put("body", body);

            //订单流水号
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            //支付金额
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//TODO 0.01为了测试
            //客户端ip地址
            paramMap.put("spbill_create_ip", "127.0.0.1");
            //回调地址
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            //二维码的类型
            paramMap.put("trade_type", "NATIVE");


            //httpclient请求微信二维码生成接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数 设置传递参数 参数是xml格式 还需携带商户key
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            //设置支持https
            client.setHttps(true);
            //发送请求
            client.post();

            //请求微信接口后返回数据
            String xml = client.getContent();
            System.out.println("xml = " + xml);

            //把xml转换为map map集合中包含微信二维码地址
            Map<String, String> wxMap = WXPayUtil.xmlToMap(xml);

            //页面需要数据返回
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", wxMap.get("result_code"));//状态码
            map.put("codeUrl", wxMap.get("code_url"));//微信支付二维码地址

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
